package top.hmtools.wxmp.server.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import top.hmtools.wxmp.AppId;
import top.hmtools.wxmp.webpage.authorize.OAuth2ATBean;
import top.hmtools.wxmp.webpage.authorize.OAuth2Tools;
import top.hmtools.wxmp.webpage.authorize.OAuth2Tools.EScope;
import top.hmtools.wxmp.webpage.authorize.OAuth2UserBean;

@Controller
public class Auth2Controller extends BaseController{

	/**
	 * 开始执行网页授权流程
	 */
	@GetMapping("/wxmp/oauth2/execute")
	public void doAuth2(){
		HttpServletRequest request = this.getRequest();
		String requestURI = request.getRequestURI();
		StringBuffer requestURL = request.getRequestURL();
		String redirect_uri = requestURL.toString().replace(requestURI, "")+"/wxmp/oauth2/userinfo";
		String oAuth2UrlStr = OAuth2Tools.getOAuth2UrlStr(AppId.appid, redirect_uri, EScope.SNSAPI_BASE, "");
		try {
			this.logger.info("获取的最终网页授权跳转URL是：{}",oAuth2UrlStr);
			this.getResponse().sendRedirect(oAuth2UrlStr);
		} catch (IOException e) {
			this.logger.error("网页授权跳转失败：",e);
		}
	}
	
	/**
	 * 网页授权流程之 获取用户信息（可以说是最后一步）
	 * @param code
	 * @param state
	 * @return
	 */
	@GetMapping("/wxmp/oauth2/userinfo")
	@ResponseBody
	public String doGetUserInfo(String code,String state){
		if(StringUtils.isEmpty(code)){
			return "code 参数为空";
		}
		//获取accesstoken 
		OAuth2ATBean accessToken = OAuth2Tools.getAccessToken(code, AppId.appid, AppId.appsecret);
		this.logger.info("accesstoken：{}",accessToken);
		
		//获取用户信息
		OAuth2UserBean userInfo = OAuth2Tools.getUserInfo(accessToken);
		this.logger.info("userinfo：{}",userInfo);
		return JSON.toJSONString(userInfo);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
